﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Mvc;

using tcm.entity;
using tcm.entity.Device;
using tcm.Filters;
using tcm.request.Device;
using tcm.response;
using tcm.utils;

namespace tcm.Controller.DeviceManage
{
    [ApiController]
    [Route("tcm/device")]
    public class DeviceController : GCCAPIControllerBase
    {
        private readonly AbsGCCContext _context;
        public DeviceController(AbsGCCContext context) : base(context)
        {
            _context = context;
        }

        #region 设备管理
        /// <summary>
        /// 查询设备列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlist")]
        [TCMAuth(permission: "equipment:device:list")]
        public DataResponse<List<DeviceSelect>> GetList([FromQuery] DeviceRequest request)
        {

            List<DeviceSelect> items=GCCEntrance.DBManager.GlobalDB.Select<DeviceSelect>()
                .WithSql("select d.*, s.site_name " +
                        " from tcm_device d " +
                        " left join tcm_site s on s.id=d.site_id" +
                        " order by d.create_date desc")
                .WhereIf(!string.IsNullOrWhiteSpace(request.device_name), item => item.device_name.Contains(request.device_name!))
                .WhereIf(request.site_id.HasValue, item => item.site_id==request.site_id.Value!)
                .WhereIf(request.type.HasValue, item => item.type==request.type.Value!)
                .WhereIf(request.status.HasValue, item => item.status==request.status.Value!)
                .OrderByDescending(item => item.create_date)
                .Count(out var count)
                .Page(request.PageIndex ?? 1, request.PageSize!=0? request.PageSize:int.MaxValue)
                .ToList();

            return HandleData(items, count);
        }

        /// <summary>
        /// 查询设备表详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("get/{id}")]
        public DataResponse<Device> GetDevice([FromRoute] long id)
        {
            var res = GCCEntrance.DBManager!.LocalDB!.Queryable<Device>().Where(x => x.id==id).First();

            return HandleData(res);
        }


        /// <summary>
        /// 添加设备
        /// </summary>
        /// <returns></returns>
        [HttpPost("add")]
        [TCMAuth(permission: "equipment:device:add")]
        public DataResponse<bool> AddDevice([FromBody] DeviceDto request)
        {
            var saveRes = false;
            try
            {

                GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
                {
                    request.Create(_context, HttpContext.GetToken()).Wait();
                    Device device = BeanUtils.copy<Device, DeviceDto>(request);
                    if (GCCEntrance.DBManager!.LocalDB!.Insert(device).ExecuteAffrows() != 1)
                    {
                        throw new Exception();
                    }
   
                    saveRes=true;
                });
            }
            catch(Exception exe)
            {
                return SystemError<bool>(exe.Message);
            }

            return HandleData(saveRes);
        }

        /// <summary>
        /// 更新设备
        /// </summary>
        /// <returns></returns>
        [HttpPost("update")]
        [TCMAuth(permission: "equipment:device:update")]
        public DataResponse<bool> UpdateDevice([FromBody] DeviceDto request)
        {
            var saveRes = false;
            if (request.id<=0)
                return SystemError<bool>("id为空");
            try
            {
                GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
                {
                    var device = GCCEntrance.DBManager.LocalDB.Select<Device>().Where(a => a.id == request.id).First();
                    if (device==null)
                        throw new Exception("设备不存在");
                    request.create_by = device.create_by;
                    request.create_date = device.create_date;
                    request.Modify(_context, HttpContext.GetToken()).Wait();

                    BeanUtils.copy<Device, DeviceDto>(request, ref device);

                    if (GCCEntrance.DBManager.LocalDB.Update<Device>(request.id).SetSource(device).ExecuteAffrows()<=0)
                    {
                        throw new Exception();
                    }      
                    saveRes=true;
                });
            }
            catch (Exception exe)
            {
                return SystemError<bool>(exe.Message);
            }
            return HandleData(saveRes);
        }

        /// <summary>
        /// 删除设备
        /// </summary>
        /// <returns></returns>
        [HttpDelete("delete/{ids}")]
        [TCMAuth(permission: "equipment:device:remove")]
        public DataResponse<bool> DeleteDevice([FromRoute] string ids)
        {
            var saveRes = false;
            if (string.IsNullOrWhiteSpace(ids))
                return SystemError<bool>("id为空");

            var msg =new StringBuilder();
            var idList = SysHelper.SpitIntArrary(ids);
            foreach (var id in idList) {
                var dbquery = GCCEntrance.DBManager.GlobalDB.Select<Order, Cabinet, Device>()
               .InnerJoin((a,  c,  e) => a.cabinet_id == c.id)
               .InnerJoin((a,  c,  e) => c.device_id == e.id)
               .Where((a, c, e) => a.status!= 1 && id == e.id)
               .ToList();

                if (dbquery!=null &&  dbquery.Count> 0)
                    _=msg.Append(id+"；");
            }
            if (!string.IsNullOrWhiteSpace(msg.ToString()))
            {
                return SystemError<bool>("设备已在使用不可删除。删除id："+ msg.ToString());
            }
            saveRes = GCCEntrance.DBManager!.LocalDB!.Delete<Device>().Where(x => idList.Contains(x.id)).ExecuteAffrows()>0;

            return HandleData(saveRes);
        }

        #endregion
    }
}
